# Copyright 2018 Tecnativa - Carlos Dauden
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import api, fields, models
from odoo.addons import decimal_precision as dp
from odoo.tools.float_utils import float_compare, float_round
import logging


_logger = logging.getLogger(__name__)


class SaleOrderLine(models.Model):
    _inherit = 'sale.order.line'

    pro_code = fields.Char(u'客户物料编码',)
    pro_name = fields.Char(u'客户物料名称')
    secondary_uom_qty = fields.Float(
        string=u'数量(桶)',
        digits=dp.get_precision('Product Unit of Measure'),
    )
    secondary_uom_tx = fields.Float(
        string=u'规格(公斤/桶)',
        ondelete='restrict',
    )

    @api.onchange('order_partner_id', 'product_id')
    def _find_line_sale_order(self):
        if self.order_partner_id:
            if self.product_id.alias_name:
                self.pro_name = self.product_id.alias_name
            if self.product_id.alias_code:
                self.pro_code = self.product_id.alias_code
            maters = self.product_id.material
            for rec in maters:
                if str(self.order_partner_id.id) == str(rec.pro.id):
                    self.pro_name = rec.pro_name
                    # _logger.info(rec.pro_name)
                    self.pro_code = rec.pro_code
                    break
            # _logger.info(self.product_id.name)
            if self.pro_name == False:
                self.pro_name = self.product_id.name

    @api.onchange('secondary_uom_tx', 'secondary_uom_qty')
    def onchange_secondary_uom(self):
        if not self.secondary_uom_tx:
            return
        factor = self.secondary_uom_tx
        qty = float_round(
            self.secondary_uom_qty * factor,
            precision_rounding=self.product_uom.rounding
        )
        if float_compare(
                self.product_uom_qty, qty,
                precision_rounding=self.product_uom.rounding) != 0:
            self.product_uom_qty = qty

    @api.onchange('product_uom_qty')
    def onchange_secondary_unit_product_uom_qty(self):
        if not self.secondary_uom_tx:
            return
        factor = self.secondary_uom_tx
        qty = float_round(
            self.product_uom_qty / (factor or 1.0),
            precision_rounding=self.product_uom.rounding
        )
        if float_compare(
                self.secondary_uom_qty, qty,
                precision_rounding=self.product_uom.rounding) != 0:
            self.secondary_uom_qty = qty

    @api.onchange('product_uom')
    def onchange_product_uom_for_secondary(self):
        if not self.secondary_uom_tx:
            return
        factor = self.secondary_uom_tx
        qty = float_round(
            self.product_uom_qty / (factor or 1.0),
            precision_rounding=self.product_uom.rounding
        )
        if float_compare(
                self.secondary_uom_qty, qty,
                precision_rounding=self.product_uom.rounding) != 0:
            self.secondary_uom_qty = qty

    @api.depends('secondary_uom_qty', 'product_uom_qty', 'discount', 'price_unit', 'tax_id')
    def _compute_amount(self):
        """
        Compute the amounts of the SO line.
        """
        for line in self:
            price = line.price_unit * (1 - (line.discount or 0.0) / 100.0)
            taxes = {}
            if line.product_id.tong:
                taxes = line.tax_id.compute_all(price, line.order_id.currency_id, line.secondary_uom_qty,
                                                product=line.product_id, partner=line.order_id.partner_shipping_id)
            else:
                taxes = line.tax_id.compute_all(price, line.order_id.currency_id, line.product_uom_qty,
                                                product=line.product_id, partner=line.order_id.partner_shipping_id)
            line.update({
                'price_tax': sum(t.get('amount', 0.0) for t in taxes.get('taxes', [])),
                'price_total': taxes['total_included'],
                'price_subtotal': taxes['total_excluded'],
            })


class SaleOrder(models.Model):
    _inherit = 'sale.order'

    tx_daxie = fields.Char(u'合计（大写）', compute='_compute_tx')
    tx_tong = fields.Float(u'共多少桶', compute='_compute_tx_tong')

    @api.depends('order_line.secondary_uom_qty')
    def _compute_tx_tong(self):
        """
        Compute the total amounts of the SO.
        """
        for order in self:
            amount = 0.0
            for line in order.order_line:
                if line.product_id.tong == False:
                    amount += line.secondary_uom_qty
            order.update({
                'tx_tong': amount,
            })

    @api.depends("amount_total")
    def _compute_tx(self):
        # just in case someone opens the budget line in form view
        for record in self:
            computed_name = self.num2chn(record.amount_total)
            record.tx_daxie = computed_name

    def IIf(self, b, s1, s2):
        if b:
            return s1
        else:
            return s2

    def num2chn(self, nin=None):
        cs = (u'零', u'壹', u'贰', u'叁', u'肆', u'伍', u'陆', u'柒', u'捌', u'玖', u'◇', u'分', u'角',
              u'圆', u'拾', u'佰', u'仟', u'万', u'拾', u'佰', u'仟', u'亿', u'拾', u'佰', u'仟', u'万')
        st = ''
        st1 = ''
        s = '%0.2f' % (nin)
        sln = len(s)
        if sln > 15:
            return None
        fg = (nin < 1)
        for i in range(0, sln - 3):
            ns = ord(s[sln - i - 4]) - ord('0')
            st = self.IIf((ns == 0)and(fg or (i == 8)or(i == 4)or(i == 0)), '', cs[ns]) + self.IIf(
                (ns == 0)and((i != 8)and(i != 4)and(i != 0)or fg and(i == 0)), '', cs[i + 13]) + st
            fg = (ns == 0)
        fg = False
        for i in [1, 2]:
            ns = ord(s[sln - i]) - ord('0')
            st1 = self.IIf((ns == 0)and((i == 1)or(i == 2)and(fg or (nin < 1))), '',
                           cs[ns]) + self.IIf((ns > 0), cs[i + 10], self.IIf((i == 2) or fg, '', '整')) + st1
            fg = (ns == 0)
        st.replace(u'亿万', u'万')
        return self.IIf(nin == 0, u'零', st + st1)
